package xq.demo.excel;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class PoiUtil{
	private String filename;
	private InputStream is;
	private Workbook wb;

	public void setFileName(String filename) {
		this.filename = filename;
	}

	public void setInputStream(InputStream is) {
		this.is = is;
	}
	
	public String getCell(int sheet, int row, int col) {
		if(wb==null) {
			if(filename==null && is==null)
				return null;
			if(is==null) {
				try {
					is = new FileInputStream(filename);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
					return null;
				}
			}
			try {
				wb = WorkbookFactory.create(is);
			} catch (EncryptedDocumentException | InvalidFormatException
					| IOException e) {
				e.printStackTrace();
				return null;
			} 
		}
		Sheet ws = wb.getSheetAt(sheet);
		Row r = ws.getRow(row);
		Cell cell = r.getCell(col);
		return cell.getStringCellValue();
	}
}
